package cn.edu.tju.elm.service;

import cn.edu.tju.core.model.User;
import cn.edu.tju.core.security.repository.UserRepository;
import cn.edu.tju.elm.repository.VirtualWalletRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class WalletMigrationService {

    private final UserRepository userRepository;
    private final VirtualWalletRepository virtualWalletRepository;
    private final VirtualWalletService virtualWalletService;

    /**
     * 为所有没有钱包的用户创建钱包
     */
    @Transactional
    public int createWalletsForExistingUsers() {
        // 获取所有用户
        List<User> allUsers = userRepository.findAll();
        int createdCount = 0;

        for (User user : allUsers) {
            // 检查用户是否已经有钱包
            boolean hasWallet = virtualWalletRepository.findByUserId(user.getId()).isPresent();

            if (!hasWallet) {
                try {
                    virtualWalletService.createWalletForUser(user);
                    createdCount++;
                    log.info("为用户 {} (ID: {}) 创建钱包成功", user.getUsername(), user.getId());
                } catch (Exception e) {
                    log.error("为用户 {} (ID: {}) 创建钱包失败: {}",
                            user.getUsername(), user.getId(), e.getMessage());
                }
            }
        }

        log.info("钱包迁移完成：共检查 {} 个用户，成功创建 {} 个新钱包",
                allUsers.size(), createdCount);
        return createdCount;
    }

    /**
     * 获取没有钱包的用户数量
     */
    @Transactional(readOnly = true)
    public long countUsersWithoutWallet() {
        List<User> allUsers = userRepository.findAll();
        return allUsers.stream()
                .filter(user -> virtualWalletRepository.findByUserId(user.getId()).isEmpty())
                .count();
    }


}